import path from "path";
import fs from "fs";
/**
 *
 * @param filePath 文件路径
 * @param data 文件内容
 * @returns Promise<null>
 * @description 传入文件路径，若路径不存在则创建文件夹，然后创建文件、写入文件内容
 */
export const writeFile = (filePath: string, data: string) => {
    return new Promise((resolve, reject) => {
        const pathSplitArr = filePath.split("\\");
        const typesFolderPath = pathSplitArr.slice(0, pathSplitArr.length - 1).join("\\");
        try {
            fs.mkdirSync(typesFolderPath, { recursive: true });
        } catch (err) {
            return reject(err);
        }
        fs.writeFile(path.resolve(typesFolderPath, pathSplitArr[pathSplitArr.length - 1]), data, err => {
            if (err) {
                console.error(err);
                reject(err);
            } else {
                resolve(null);
            }
        });
    });
};

// 使用 fs.promises.rmdir 删除文件夹
export const deleteFolder = async (folderPath: string) => {
    try {
        await fs.promises.rm(folderPath, { recursive: true, force: true });
    } catch (err) {
        console.error('删除文件夹时出错:', err);
    }
}
